﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JukeBoxLib
{
    public class TagLibSharpUtil
    {

        public static Track TagLib2Track(string path)
        {
            Track track = new Track();
            System.IO.FileInfo fileinfo = new System.IO.FileInfo(path);
            if (!fileinfo.Exists)
                return null;

            TagLib.File file = TagLib.File.Create(path);

            track.Artists = file.Tag.JoinedPerformers;
            track.Title = file.Tag.Title;
            track.Album = file.Tag.Album;
            track.AlbumArtists = file.Tag.JoinedAlbumArtists;
            track.Composers = file.Tag.JoinedComposers;
            track.Year = file.Tag.Year;
            track.TrackNumber = file.Tag.Track;
            track.TrackCount = file.Tag.TrackCount;
            track.Duration = file.Properties.Duration;
            track.AudioBitrate = file.Properties.AudioBitrate;
            track.ID3v1 = file.TagTypes == TagLib.TagTypes.Id3v1;
            track.ID3v2 = file.TagTypes == TagLib.TagTypes.Id3v2;
            track.DiscNumber = file.Tag.Disc;
            track.DiscCount = file.Tag.DiscCount;
            track.Genre = file.Tag.JoinedGenres;
            track.Conductor = file.Tag.Conductor;

            //track.HasPicture = file.Tag.Pictures != null;

            track.FileName = fileinfo.FullName;
            track.Length = fileinfo.Length;

            System.IO.FileStream fs = System.IO.File.OpenRead(path);
            byte[] fbuffer = new byte[file.InvariantEndPosition - file.InvariantStartPosition];
            fs.Seek(file.InvariantStartPosition, System.IO.SeekOrigin.Begin);
            fs.Read(fbuffer, 0, (int)(file.InvariantEndPosition - file.InvariantStartPosition));
            
            fs.Close();
            track.CRC = new HexVal(CRC32.Compute(fbuffer));

            return track;
        }
    }
}
